package me.qi.kancha.controller;

import cn.hutool.core.io.file.FileNameUtil;
import me.qi.kancha.controller.base.BaseController;
import me.qi.kancha.support.TencentCOS;
import me.qi.kancha.vo.oss.UploadVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author sun
 * @date 2022/9/23 6:11
 * @modified By：
 */
@RestController
@RequestMapping("/cos")
public class CosController extends BaseController {

    private final TencentCOS tencentCOS;

    @Value("${file.tmp}")
    private String tmp;

    public CosController(TencentCOS tencentCOS) {
        this.tencentCOS = tencentCOS;
    }

    @PostMapping("/upload")
    public Map<String, String> upload(@Validated UploadVo param, BindingResult error) throws IOException {
        checkBindingResult(error);
        MultipartFile file = param.getFile();
        String yearMonth = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMM"));
        String fileName = String.format("%s.%s", UUID.randomUUID().toString(),
                FileNameUtil.extName(file.getOriginalFilename()));
        String objectName = String.format("%s/%s/%s", param.getType(), yearMonth, fileName);
        File tmpFile = new File(tmp, fileName);
        file.transferTo(tmpFile);
        String url = tencentCOS.upload(tmpFile, objectName);
        Map<String, String> result = new HashMap<>();
        result.put("url", url);
        return result;
    }

}
